import React, { useRef, useState, useMemo, useReducer } from 'react'

function Container({ children }) {
	const [showLoading, setShowLoading] = useState(false)

	const renderChildren = useMemo(
		() =>
			typeof children === 'function'
				? children({ setShowLoading })
				: null,
		[children],
	)

	//const renderChildren = children({ setShowLoading })

	return (
		<div>
			{renderChildren}
			{showLoading && (
				<img src="https://www.bing.com/th/id/OGC.aaa5a5b38a9203508adf5964526e0939?pid=1.7&rurl=https%3a%2f%2fimg.zcool.cn%2fcommunity%2f01f9a1597707f5a8012193a35c6531.gif&ehk=RCusQe%2fR44r64pfxzB9ufBvV4Qt1kD1MnlhN9mmRshw%3d"></img>
			)}
		</div>
	)
}

Container = React.memo(Container, (prevProps, nextProps) => {
	// 返回 true 不更新
	console.log('prevProps', prevProps)
	console.log('nextProps', nextProps)
	return true
})
export default function RenderProps() {
	const setLoading = useRef(null)
	console.log('父组件渲染')
	const [, forceUpdate] = useReducer((pre) => pre + 1, 0)
	return (
		<div>
			<Container>
				{({ setShowLoading }) => {
					console.log('子组件函数执行渲染')
					setLoading.current = setShowLoading
					return (
						<div>
							<button onClick={() => setShowLoading(true)}>
								开始loading
							</button>
						</div>
					)
				}}
			</Container>
			<button
				onClick={() => setLoading.current && setLoading.current(false)}
			>
				取消 loading
			</button>
			<button onClick={forceUpdate}>父组件渲染</button>
		</div>
	)
}
